# ----------------------------------------------------------------------------
#       Copyright (C) 2013-2014 Huynh Vi Lam  <domovilam@gmail.com>
#
#       This file is part of pimucha.
#
#	This program is free software: you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation, either version 3 of the License, or
#	(at your option) any later version.
#	
#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#	
#	You should have received a copy of the GNU General Public License
#	along with this program.  If not, see <http://www.gnu.org/licenses/>.
# ----------------------------------------------------------------------------

import logging,threading,time
from .classlogf import CLASSLOGF


logger = logging.getLogger()


class SYSLOGF(CLASSLOGF):

    def __init__(self,Logfile):
        CLASSLOGF.__init__(self,Logfile)
        self.name = 'SYS'
        self.setup = False
        self.servercmds = {'STARTS':self.starts,'STOPS':self.stops}
        self.features = []

    def close(self):
        CLASSLOGF.close(self)

    def tsetup(self):
        """
        Setup 
        """
        self.open()
        if self.opened:
            self.setup = True
 
    def rxsysevt(self):
        """
        Receiving event :
        Sending to targets :
        """
        while not self.stop:
            line = self.read()
            if line:
                for target in self.features:
                    target.send(line)
            else:
                time.sleep(1)			

    def write(self, line):
        logger.debug("Writing %s to logfile %s",line,self._logfile)
        CLASSLOGF.write(self, line)
 
    def starts(self,dm=True):
        tt = threading.Thread(target=self.rxsysevt)
        tt.name = 'ThreadSYSLOGF'
        if dm: tt.daemon = True
        tt.start()
        print ('%s started and active...' % tt.name)

    def stops(self):
        logger.debug("Break STOP logfile %s",self._logfile)
        self.stop = True
        self.close()

